#include "render.h"
#include "system.h"
#include "log.h"

#include <string.h>

#include <jni.h>
#include <android/log.h>

extern JNIEnv* globalJavaEnv;
extern jobject globalJNIInterface;

int ufoRenderText(const char *text, ufoRect *rect, const char *font, int fontSize, int blod, ufoColor color, int format, unsigned char *output)
{  
	int wh = 0;
	jbyteArray _output = 0;
	jclass JNIInterfaceClass;
	jmethodID methodId;
	
	JNIInterfaceClass = (*globalJavaEnv)->GetObjectClass(globalJavaEnv, globalJNIInterface);
	methodId = (*globalJavaEnv)->GetMethodID(globalJavaEnv, JNIInterfaceClass, "renderText", "(Ljava/lang/String;IIIFFFF[B)I");
	
	if ( !(format & UFO_TEXT_CALCRECT) )
		_output = (*globalJavaEnv)->NewByteArray(globalJavaEnv, (int)(rect->right)*(int)(rect->bottom)*4);
	  
	jstring jText = (*globalJavaEnv)->NewStringUTF(globalJavaEnv, text);
	
	wh = (*globalJavaEnv)->CallIntMethod(globalJavaEnv, globalJNIInterface, methodId, 
		jText, fontSize, blod, format, 
		color.red, color.green, color.blue, rect->right-rect->left, _output);

	(*globalJavaEnv)->DeleteLocalRef(globalJavaEnv, jText);
	
	if (format & UFO_TEXT_CALCRECT) {
		rect->left = 0;
		rect->top = 0;
		rect->right = wh>>16;
		rect->bottom = wh&0x0000FFFF;
	}
	else {
		jbyte * olddata = (jbyte*)(*globalJavaEnv)->GetByteArrayElements(globalJavaEnv, _output, 0);
		memcpy(output, olddata, (int)rect->right*(int)rect->bottom*4);
		(*globalJavaEnv)->DeleteLocalRef(globalJavaEnv, _output);
	}
	
	return 1;
}

int ufoBeginRender(void* param)
{

	return 1;
}

int ufoEndRender(void* param)
{

	return 1;
}